{% extends "后台管理/template.html" %}

{% block title %}
    用户列表
{% endblock %}

{% block css %}
<style>
    .user-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
    }
    
    .search-box {
        margin-bottom: 20px;
        background: #fff;
        padding: 24px;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        border: 1px solid #ebeef5;
    }
    
    .search-box .input-group {
        max-width: 500px;
        position: relative;
    }
    
    .search-box .form-control {
        height: 42px;
        padding-left: 15px;
        border-radius: 21px;
        border: 2px solid #ebeef5;
        transition: all 0.3s ease;
        padding-right: 100px; /* 为按钮预留空间 */
    }
    
    .search-box .form-control:focus {
        box-shadow: none;
        border-color: #696cff;
    }
    
    .search-box .form-control::placeholder {
        color: #909399;
        font-size: 14px;
    }
    
    .search-box .input-group-append {
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        z-index: 10;
    }
    
    .search-box .input-group-append .btn {
        height: 32px;
        padding: 0 20px;
        background: #696cff;
        color: #fff;
        border-radius: 16px;
        border: none;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 5px;
        transition: all 0.3s ease;
    }
    
    .search-box .input-group-append .btn:hover {
        background: #5f62e6;
        transform: translateY(-1px);
    }
    
    .search-box .input-group-append .btn:active {
        transform: translateY(0);
    }
    
    .search-box .input-group-append .btn .bx {
        font-size: 18px;
    }
    
    /* 搜索结果提示 */
    .search-result-tip {
        margin-top: 10px;
        color: #909399;
        font-size: 14px;
        padding-left: 15px;
    }
    
    .search-result-tip span {
        color: #696cff;
        font-weight: 500;
        margin: 0 3px;
    }
    
    .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }
    
    .user-table th,
    .user-table td {
        vertical-align: middle !important;
        max-width: 200px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .user-table .user-id-column {
        max-width: 280px;
    }
    
    .user-table .time-column {
        min-width: 150px;
    }
    
    .user-table .avatar-column {
        width: 60px;
        min-width: 60px;
    }
    
    .user-table .action-column {
        width: 150px;
        min-width: 150px;
    }
    
    .pagination .page-link {
        padding: 0.5rem 0.75rem;
        line-height: 1;
    }
    
    .pagination .bx {
        display: inline-block;
        width: 14px;
        text-align: center;
    }
    
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255,255,255,0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 搜索框 -->
    <div class="search-box">
        <div class="row">
            <div class="col-md-8 d-flex align-items-center justify-content-between">
                <div class="input-group">
                    <input 
                        type="text" 
                        class="form-control" 
                        id="searchInput" 
                        placeholder="输入用户名、账号或用户ID进行搜索..."
                        onkeyup="handleKeyUp(event)"
                    >
                    <div class="input-group-append">
                        <button class="btn" type="button" onclick="searchUsers()">
                            <i class='bx bx-search'></i>
                            <span>搜索</span>
                        </button>
                    </div>
                </div>
                <div class="search-result-tip" id="searchResultTip" style="display: none;">
                    共找到<span id="searchResultCount">0</span>个匹配结果
                </div>
                <button class="btn btn-danger ms-3" id="batchDeleteBtn" style="display: none;">
                    <i class='bx bx-trash me-1'></i>
                    批量删除 (<span id="selectedCount">0</span>)
                </button>
            </div>
        </div>
    </div>

    <!-- 用户列表表格 -->
    <div class="table-responsive">
        <table class="table table-hover user-table">
            <thead>
                <tr>
                    <th class="text-center" style="width: 40px;">
                        <input type="checkbox" class="form-check-input" id="selectAll">
                    </th>
                    <th class="avatar-column">头像</th>
                    <th style="min-width: 100px">用户名</th>
                    <th style="min-width: 120px">账号</th>
                    <th class="user-id-column" title="用户ID">用户ID</th>
                    <th class="time-column" title="创建时间">创建时间</th>
                    <th class="time-column" title="更新时间">更新时间</th>
                    <th class="action-column">操作</th>
                </tr>
            </thead>
            <tbody id="userTableBody">
                <!-- 用户数据将通过JS动态插入 -->
            </tbody>
        </table>
    </div>

    <!-- 分页器 -->
    <div class="pagination">
        <nav aria-label="Page navigation">
            <ul class="pagination" id="pagination">
                <!-- 分页按钮将通过JS动态插入 -->
            </ul>
        </nav>
    </div>

    <!-- 加载中遮罩 -->
    <div class="loading-overlay" id="loadingOverlay" style="display: none;">
        <div class="spinner-border text-primary" role="status">
            <span class="sr-only">加载中...</span>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">删除确认</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-0">确定要删除该用户吗？此操作不可恢复！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                        <i class='bx bx-trash me-1'></i>确认删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 批量删除确认模态框 -->
    <div class="modal fade" id="batchDeleteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">批量删除确认</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p class="mb-0">确定要删除选中的 <span id="deleteCount" class="text-danger fw-bold">0</span> 个用户吗？此操作不可恢复！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmBatchDeleteBtn">
                        <i class='bx bx-trash me-1'></i>确认删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editForm">
                        <!-- 头像上传 -->
                        <div class="mb-3 text-center">
                            <img id="previewAvatar" class="rounded-circle mb-2" style="width: 100px; height: 100px; object-fit: cover; cursor: pointer;" onclick="document.getElementById('avatarInput').click()">
                            <input type="file" id="avatarInput" accept="image/*" style="display: none" onchange="previewImage(this)">
                            <div class="small text-muted">点击头像更换</div>
                        </div>
                        
                        <!-- 用户名 -->
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" id="editUsername" placeholder="请输入新的用户名">
                        </div>
                        
                        <!-- 密码 -->
                        <div class="mb-3">
                            <label class="form-label">密码</label>
                            <input type="password" class="form-control" id="editPassword" placeholder="不修改请留空">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitEdit()">
                        <i class='bx bx-save me-1'></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let currentPage = 1;
const pageSize = 10;
let totalPages = 1; // 设置默认值

let deleteModal = null;
let userToDelete = null;
let batchDeleteModal = null;
let selectedUsers = new Set();
let editModal = null;
let currentEditUser = null;
let avatarChanged = false;

// 获取用户列表
async function getUserList(page = 1) {
    try {
        showLoading();
        const response = await fetch('/api/users/get_user_list/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded', // 表单方式
            },
            body: `page=${page}&page_size=${pageSize}`
        });
        
        const data = await response.json();
        
        if(data.code === 200) {
            renderUserList(data.data.users);
            renderPagination(data.data.total);
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('获取用户列表失败:', error);
        showToast('获取用户列表失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 渲染用户列表
function renderUserList(users) {
    const tbody = document.getElementById('userTableBody');
    tbody.innerHTML = '';
    
    users.forEach(user => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td class="text-center">
                <input type="checkbox" class="form-check-input user-checkbox" 
                    data-user-id="${user.user_id}"
                    ${selectedUsers.has(user.user_id) ? 'checked' : ''}>
            </td>
            <td>
                <img src="${user.avatar}" class="user-avatar" alt="avatar">
            </td>
            <td>${user.username}</td>
            <td>${user.account}</td>
            <td>${user.user_id}</td>
            <td>${formatDateTime(user.create_time)}</td>
            <td>${formatDateTime(user.update_time)}</td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="editUser('${user.user_id}')">
                    <i class='bx bx-edit-alt'></i> 编辑
                </button>
                <button class="btn btn-sm btn-danger ms-1" onclick="deleteUser('${user.user_id}')" style="background: #ff3e1d; border-color: #ff3e1d;">
                    <i class='bx bx-trash'></i> 删除
                </button>
            </td>
        `;
        tbody.appendChild(tr);
    });
    
    updateBatchDeleteButton();
}

// 渲染分页器
function renderPagination(total) {
    totalPages = Math.ceil(total / pageSize);  // 更新全局变量
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';
    
    // 上一页
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage - 1})">
            <i class='bx bxs-chevrons-left'></i>
        </a>
    `;
    pagination.appendChild(prevLi);
    
    // 页码
    for(let i = 1; i <= totalPages; i++) {
        const li = document.createElement('li');
        li.className = `page-item ${currentPage === i ? 'active' : ''}`;
        li.innerHTML = `
            <a class="page-link" href="javascript:void(0)" onclick="changePage(${i})">${i}</a>
        `;
        pagination.appendChild(li);
    }
    
    // 下一页
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="javascript:void(0)" onclick="changePage(${currentPage + 1})">
            <i class='bx bxs-chevrons-right'></i>
        </a>
    `;
    pagination.appendChild(nextLi);
}

// 切换页码
function changePage(page) {
    // 打印调试信息
    console.log('切换到页码:', page);
    console.log('当前页码:', currentPage);
    console.log('总页数:', totalPages);

    if(page < 1 || page > totalPages) {
        console.log('页码超出范围');
        return;
    }
    
    currentPage = page;
    getUserList(page);
}

// 搜索用户
async function searchUsers() {
    const keyword = document.getElementById('searchInput').value.trim();
    
    if(!keyword) {
        // 如果搜索框为空，恢复显示所有用户
        getUserList(1);
        document.getElementById('searchResultTip').style.display = 'none';
        return;
    }
    
    try {
        showLoading();
        const response = await fetch('/api/users/search_user/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `keyword=${encodeURIComponent(keyword)}`
        });
        
        const data = await response.json();
        
        if(data.code === 200) {
            renderUserList(data.data);
            // 显示搜索结果数量
            document.getElementById('searchResultCount').textContent = data.data.length;
            document.getElementById('searchResultTip').style.display = 'block';
            // 隐藏分页器
            document.getElementById('pagination').style.display = 'none';
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('搜索用户失败:', error);
        showToast('搜索失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 处理回车键搜索
function handleKeyUp(event) {
    if(event.key === 'Enter') {
        searchUsers();
    }
}

// 编辑用户
function editUser(userId) {
    // 查找当前用户数据
    const userRow = document.querySelector(`[data-user-id="${userId}"]`).closest('tr');
    const avatar = userRow.querySelector('.user-avatar').src;
    const username = userRow.querySelector('td:nth-child(3)').textContent;
    
    // 设置当前编辑的用户信息
    currentEditUser = {
        user_id: userId,
        avatar: avatar,
        username: username
    };
    
    // 填充表单
    document.getElementById('previewAvatar').src = avatar;
    document.getElementById('editUsername').value = username;
    document.getElementById('editPassword').value = '';
    
    // 重置标记
    avatarChanged = false;
    
    // 显示模态框
    editModal.show();
}

// 预览图片
function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('previewAvatar').src = e.target.result;
            avatarChanged = true;
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// 提交编辑
async function submitEdit() {
    if(!currentEditUser) return;
    
    try {
        showLoading();
        
        // 构建表单数据
        const formData = new FormData();
        formData.append('user_id', currentEditUser.user_id);
        
        // 只添加修改的字段
        const newUsername = document.getElementById('editUsername').value.trim();
        const newPassword = document.getElementById('editPassword').value.trim();
        const avatarInput = document.getElementById('avatarInput');
        
        if(newUsername !== currentEditUser.username) {
            formData.append('username', newUsername);
        }
        
        if(newPassword) {
            formData.append('password', newPassword);
        }
        
        if(avatarChanged && avatarInput.files[0]) {
            formData.append('avatar', avatarInput.files[0]);
        }
        
        const response = await fetch('/api/users/edit_user_info/', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if(data.code === 200) {
            showToast('编辑成功', 'success');
            editModal.hide();
            getUserList(currentPage); // 刷新列表
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('编辑用户失败:', error);
        showToast('编辑失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 删除用户
function deleteUser(userId) {
    userToDelete = userId;
    deleteModal.show();
}

// 执行删除操作
async function executeDelete(userId) {
    try {
        showLoading();
        const response = await fetch('/api/users/delete_user/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `user_id=${userId}`
        });
        
        const data = await response.json();
        
        if(data.code === 200) {
            showToast('删除成功', 'success');
            
            // 重新加载当前页数据
            const tbody = document.getElementById('userTableBody');
            if(tbody.children.length === 1 && currentPage > 1) {
                currentPage--;
            }
            getUserList(currentPage);
        } else {
            throw new Error(data.message);
        }
    } catch(error) {
        console.error('删除用户失败:', error);
        showToast('删除失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 格式化日期时间
function formatDateTime(dateStr) {
    const date = new Date(dateStr.replace(/-/g, '/'));
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 显示加载中
function showLoading() {
    document.getElementById('loadingOverlay').style.display = 'flex';
}

// 隐藏加载中
function hideLoading() {
    document.getElementById('loadingOverlay').style.display = 'none';
}

// 初始化删除模态框
function initDeleteModal() {
    deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    
    // 监听确认删除按钮点击
    document.getElementById('confirmDeleteBtn').addEventListener('click', async () => {
        deleteModal.hide();
        await executeDelete(userToDelete);
    });
}

// 初始化批量删除功能
function initBatchDelete() {
    batchDeleteModal = new bootstrap.Modal(document.getElementById('batchDeleteModal'));
    
    // 全选/取消全选
    document.getElementById('selectAll').addEventListener('change', function(e) {
        const checkboxes = document.querySelectorAll('.user-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = e.target.checked;
            const userId = checkbox.dataset.userId;
            if(e.target.checked) {
                selectedUsers.add(userId);
            } else {
                selectedUsers.delete(userId);
            }
        });
        updateBatchDeleteButton();
    });
    
    // 监听单个复选框变化
    document.getElementById('userTableBody').addEventListener('change', function(e) {
        if(e.target.classList.contains('user-checkbox')) {
            const userId = e.target.dataset.userId;
            if(e.target.checked) {
                selectedUsers.add(userId);
            } else {
                selectedUsers.delete(userId);
            }
            updateBatchDeleteButton();
        }
    });
    
    // 批量删除按钮点击
    document.getElementById('batchDeleteBtn').addEventListener('click', function() {
        document.getElementById('deleteCount').textContent = selectedUsers.size;
        batchDeleteModal.show();
    });
    
    // 确认批量删除
    document.getElementById('confirmBatchDeleteBtn').addEventListener('click', async function() {
        batchDeleteModal.hide();
        await executeBatchDelete();
    });
}

// 更新批量删除按钮状态
function updateBatchDeleteButton() {
    const btn = document.getElementById('batchDeleteBtn');
    const count = selectedUsers.size;
    document.getElementById('selectedCount').textContent = count;
    btn.style.display = count > 0 ? 'block' : 'none';
}

// 执行批量删除
async function executeBatchDelete() {
    if(selectedUsers.size === 0) return;
    
    showLoading();
    let successCount = 0;
    let failCount = 0;
    
    try {
        // 串行执行删除操作，确保每个请求都能得到处理
        for(const userId of selectedUsers) {
            try {
                const response = await fetch('/api/users/delete_user/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `user_id=${userId}`
                });
                
                const data = await response.json();
                if(data.code === 200) {
                    successCount++;
                } else {
                    failCount++;
                }
            } catch(err) {
                failCount++;
            }
        }
        
        // 显示结果
        if(successCount > 0) {
            showToast(`成功删除 ${successCount} 个用户${failCount > 0 ? `，${failCount} 个失败` : ''}`, 'success');
        } else {
            showToast(`删除失败`, 'error');
        }
        
        // 清空选择
        selectedUsers.clear();
        updateBatchDeleteButton();
        
        // 重新加载数据
        await getUserList(currentPage);
    } catch(error) {
        console.error('批量删除失败:', error);
        showToast('批量删除失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 初始化模态框
function initModals() {
    deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    batchDeleteModal = new bootstrap.Modal(document.getElementById('batchDeleteModal'));
    editModal = new bootstrap.Modal(document.getElementById('editModal'));
}

// 页面加载完成后获取用户列表
document.addEventListener('DOMContentLoaded', () => {
    getUserList();
    initModals();
    initBatchDelete();
});
</script>
{% endblock %}


{% block nav_left %}
{% endblock %}


{% block NavBar %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block footer %}
{% include '后台管理/components/Footer.html' %}
{% endblock %}